import os
import shutil
import schedule
import time
# import datatime

from repoGItHandle import clone_github_repo ,check_and_pull,is_git_remote_change
from getData import createFile,getLinkAndLocalRepoPath

# excel所在仓库的远程链接
xls_remote_repo_ssh_link="git@gitee.com:zz--yy/ysyx-student-cv-data.git"

#设置保存数据xls的本地仓库所在路径
xls_local_repo_path= "githubXlsRepo"

#保存数据的xls的路径
cv_xls_name   = "repo.xls"
cv_xls_path   = os.path.join(xls_local_repo_path, cv_xls_name )


# 设置保存学生简历本地仓库所在的路径
student_cv_local_repo_dir_path = "./StudentCVRepo/"

def cloneAndUpdateLocalRepoFromRemoteLink(local_repo_path,local_repo_parent_dir_path,repo_link):
    if os.path.exists(local_repo_path):  # 仓库存在
        # 检查仓库远程链接是否发生变化
        is_change = is_git_remote_change(local_repo_path, repo_link)
        if (is_change):
            shutil.rmtree(local_repo_path)  # 删除之前的仓库，
            createFile(local_repo_path,local_repo_parent_dir_path)  # 在指定目录创建对应仓库文件夹
            clone_github_repo(repo_link, local_repo_path)  # 克隆仓库
        else:  # 没有发生变化
            check_and_pull(repo_link, local_repo_path)  # pull仓库更新仓库
    else:  # 仓库不存在
        createFile(local_repo_path,local_repo_parent_dir_path)  # 在指定目录创建对应仓库文件夹
        clone_github_repo(repo_link, local_repo_path)  # 克隆仓库
        # print(f"{student_local_repo_path}不存在")
def gitRepoUpdate(repo_xls_path,repo_dir_path):
    repo_path_links = getLinkAndLocalRepoPath(repo_xls_path, repo_dir_path)
    for one_repo_path_link in repo_path_links:
        [student_local_repo_path, repo_link] = one_repo_path_link   # 拆分出仓库名字和仓库的远程链接
        cloneAndUpdateLocalRepoFromRemoteLink(student_local_repo_path,repo_dir_path,repo_link)

def gitRepoUpdataFromXls():
    # 更新excel仓库中的
    # start_time = datatime.now()
    cloneAndUpdateLocalRepoFromRemoteLink(xls_local_repo_path, "./", xls_remote_repo_ssh_link)
    if not os.path.exists(student_cv_local_repo_dir_path):
        createFile(student_cv_local_repo_dir_path,"./")  # 在指定目录创建对应仓库文件夹
    # 更新excel中保存链接的仓库
    gitRepoUpdate(cv_xls_path, student_cv_local_repo_dir_path)
    print(f" update finish ")
    # end_time = datatime.now()
    # print(f"run time {end_time-start_time} ")

# python内部自动执行
#schedule.every(1).hour.do(gitRepoUpdataFromXls)
#while True:
#    schedule.run_pending()
#    time.sleep(600) # 10分钟检查一次


gitRepoUpdataFromXls()